import requests


class TiebaSpider:
    def __init__(self, search_name, spider_page_num):
        self.search_name = search_name
        self.spider_page_num = spider_page_num
        self.url_temp = "https://tieba.baidu.com/f?kw=" + self.search_name + "&ie=utf-8&pn={}"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}

    def get_tieb_url(self):
        """
        构造url列表
        @return:
        """
        # url_list = []
        # for i in range(self.spider_page_num):
        #     url_list.append(self.url_temp.format(i * 50))

        # 列表表达式

        return [self.url_temp.format(i * 50) for i in range(self.spider_page_num)]

    def parse_url(self, url):
        """
        发送请求，获取响应
        @param url: url
        @return:
        """
        print(url)
        response = requests.get(url, headers=self.headers)
        result = response.content.decode("utf-8")
        return result

    def save_html(self, html_str, page_num):
        """
        保存html数据
        @param html_str: 获取的html字符串数据
        @param page_num: 获取的页码
        @return:
        """
        open_path = "./tieba_html/{}_第{}页.html".format(self.search_name, page_num)
        with open(open_path, "w", encoding="utf-8") as file:
            file.write(html_str)

    def run(self):
        """
        实现主要逻辑
        @return:
        """
        # 构造url列表
        url_list = self.get_tieb_url()
        # 遍历，发送请求，获取响应
        for url in url_list:
            html_str = self.parse_url(url)
            # 保存数据
            self.save_html(html_str, url_list.index(url) + 1)


if __name__ == '__main__':
    tieba_spider = TiebaSpider("库里", 5)
    tieba_spider.run()
